package com.qdlc.p2p.biz.task.flow;


import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.qdlc.p2p.biz.task.impl.FlowBorrowTask;
import com.qdlc.p2p.biz.task.impl.FlowTenderTask;

/**
 * 流转标任务队列
 * @author wjx
 * @version 2.0
 * @date 2015年5月28日 下午3:58:07
 */
public class FlowJobQueue<T> {

	
	private Queue<T> queue = new ConcurrentLinkedQueue<T>();
	private Lock LOCK=new ReentrantLock();
	private FlowLoanTask task;
	
    private static class LazyHolder {
        // 投标相关队列
        private static final FlowJobQueue <FlowValueEvent> TENDER_INSTANCE =new FlowJobQueue<FlowValueEvent>(new FlowTenderTask());
        // 标相关队列
        private static final FlowJobQueue <FlowValueEvent> BORROW_INSTANCE = new FlowJobQueue<FlowValueEvent>(new FlowBorrowTask());
    }


    
    /**
     * 投标队列实例化
     * @return
     */
    public static FlowJobQueue <FlowValueEvent> getTenderInstance() {
        return LazyHolder.TENDER_INSTANCE;
    }

    /**
     * 标队列实例化
     * @return
     */
    public static FlowJobQueue <FlowValueEvent> getBorrowInstance() {
        return LazyHolder.BORROW_INSTANCE;
    }
    

    


    
    private FlowJobQueue(FlowLoanTask task){
		super();
		this.task = task;
    }

    

	public void offer(T model) {
		if (!queue.contains(model)) {
			queue.offer(model);
			try {
				LOCK.lock();
				task.execute();
			}finally{
				LOCK.unlock();
			}

		}
	}

	public  void offer(List<T> ts) {
		for (int i = 0; i < ts.size(); i++) {
			T t = ts.get(i);
			if (!queue.contains(t)) {
				queue.offer(t);
			}
		}
		try {
			LOCK.lock();
			task.execute();
		}finally{
			LOCK.unlock();
		}
	}

	public  T poll() {
		return queue.poll();
	}

	public  T peek() {
		return queue.peek();
	}

	public  void remove(T model) {
		queue.remove(model);
	}

	public int size() {
		return queue.size();
	}
	public  boolean isEmpty() {
		try {
			LOCK.lock();
			return queue.isEmpty();
		} finally {
			LOCK.unlock();
		}
		
	}

	public  void stop() {
		task.stop();
	}
	



}
